import express from 'express';
import React from 'react';
import path from 'path';
import { renderToString } from 'react-dom/server';
import { RouterContext, match } from 'react-router';
import { Provider } from 'react-redux';
import template from 'art-template';
import routes from '../src/js/routes';
import configureStore from '../src/js/store';
import initAction from './route-init-action';

const app = express();

//设置模板引擎
app.set('views', path.join(__dirname, 'views'));
template.defaults.extname='.html';
app.engine('html', function(filePath, options, callback){
    callback(null, template(filePath, options));
});
app.set('view engine', 'html');

//静态资源
// app.use(express.static(path.join(__dirname, '../dist')));
app.use((req, res, next) => {
    // 如果url为/有可能会去找静态目录下的index.html文件，
    // 如果存在index.html则会当作静态文件直接返回，从而不会往下执行后面的app.use，
    // 所以这里的静态资源应该要排除掉/
    if(req.url==='/'){
        next();
    }else{
        express.static(path.join(__dirname, '../dist'))(req, res, next);
    }
});

app.use((req, res) => {
    match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
        if (err) {
            res.status(500).end(`Internal Server Error ${err}`);
        } else if (redirectLocation) {
            res.redirect(redirectLocation.pathname + redirectLocation.search);
        } else if (renderProps) {
            const store = configureStore();
            const render = () => {
                const html = renderToString(
                    <Provider store={store}>
                        <RouterContext {...renderProps} />
                    </Provider>
                );
                res.render('index', {
                    __html__: html,
                    __state__: JSON.stringify(store.getState())
                })
            };

            if(initAction[req.url]) {
                //页面有初始化动作的
                store.dispatch(initAction[req.url]()).then(render);
            }else{
                render();
            }
        } else {
            res.status(404).end('Not found');
        }
    });
});

app.listen(8080, function() {
    console.log('🌎 Listening on port %d', 8080);
});